<?php
/**
 *	[TWCMS] (C)2012 TongWang Inc.
 *	$Id: category.lib.php 2 2013-04-27 07:14:17Z nanown@qq.com $
 *
 *导航栏模块
 *@limit	最大显示数
 *@level	显示child(子级)、parent(父级)、sibling(同级)、top(顶级)、为空则不分级
 *@mid		显示指定的内容模型mid
 *@incid	包含CID
 *@notcid	不包含CID
 */
class category{
	function __construct($C) {
		$limitSql = ($limit = intC($C, 'limit')) ? ' LIMIT '.$limit : '';

		$sqlArr = array();
		$levelSql = $this->getLevelSql($C); empty($levelSql) || $sqlArr[] = $levelSql;
		$mid = intC($C, 'mid'); empty($mid) || $sqlArr[] = 'mid='.$mid;
		$incid = _intC($C, 'incid'); empty($incid) || $sqlArr[] = 'cid IN ('.$incid.')';
		$notcid = _intC($C, 'notcid'); empty($notcid) || $sqlArr[] = 'cid NOT IN ('.$notcid.')';
		$whereSql = empty($sqlArr) ? '' : ' WHERE '.implode(' AND ', $sqlArr);

		if($_ENV->G['ishtml']) {	#静态
			$field = 'cid,mid,upid,categoryname,dir,parentdir,cate_url';
		}else{
			$field = 'cid,mid,categoryname,dir';
		}

		$sql = 'SELECT '.$field.' FROM `'.TW_DBPRE.'category`'.$whereSql.' ORDER BY `orderby` ASC'.$limitSql;
		$query = $_ENV->db->query($sql);
		$data = array();
		while($row = $_ENV->db->fetch_array($query)) {
			if($row['mid'] == 1) {
				$row['url'] = $row['dir'];
			}else{
				if($_ENV->G['ishtml']) {	#静态
					$url = dirname(rep_url($row['cate_url'], $row['parentdir'], $row['dir'], $row['cid'])).'/';
				}elseif($_ENV->G['isfhtml'] && $_ENV->G['custom_cate']) { #分类页伪静态高级
					$url = $row['dir'].'/';
				}else{	#伪静态/动态
					$url = (empty($_ENV->G['isfhtml']) ? 'index.php?u=' : '').$_ENV->G['url_cate'].'-'.$row['cid'].$_ENV->G['url_cate_suffix'];
				}
				$row['url'] = $_ENV->G['webdir'].$url;
			}
			$data[] = $row;
		}
		$this->data = $data;
	}

	function getLevelSql(&$C) {
		if(empty($C['level'])) return '';
		switch($C['level']) {
			case 'child':
				return 'upid='.$_ENV->V['cid'];
			case 'parent':
				return 'upid=(SELECT upid FROM `'.TW_DBPRE.'category` WHERE cid='.$_ENV->V['upid'].')';
			case 'sibling':
				return 'upid='.$_ENV->V['upid'];
			case 'top':
				return 'upid=0';
			default:
				return '';
		}
	}
}